#!/usr/bin/env python 2.7
# -*- coding: utf-8 -*-
# @Time      :2020/11/27
# @Author    :Erinyu
# @Email     :yuailing@bbdservice.com
# @File      :IC_Past6MonsLoanApprovalQueryOrgCnt
# @Software  :PyCharm

'''eof
name:个人近6个月贷款审批查询机构数
code:IC_Past6MonsLoanApprovalQueryOrgCnt
tableName:
columnName:
groups:个人征信模块
dependencies:IC_DSJ
type:常用指标
datasourceType:在线指标
description:
eof'''

import json
import sys
import re
import datetime

reload(sys)
sys.setdefaultencoding('utf-8')

null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']

def getTable(data, tableName, occurTimes, iteratorTimes):
    '''
        获取表信息
        :param data:表上层的字典对象
        :param tableName:表的名字
        :param occurTimes:表出现的次数，如果是0代表此表可以不出现，如果是1代表此表必须出现
        :param iteratorTimes:下级字段出现的次数，如果是0代表下级字段可以不出现，如果是1代表下级字段必须出现
        :return:该表全部数据  返回[{}]为异常缺失，返回0为正常缺失，其他返回正常数组
        '''
    try:
        table = data.get(tableName)
        if occurTimes == 0:
            if table is None or (table == "" and iteratorTimes == 0):
                return 0
            elif isinstance(table, list) is False or len(table) == 0 or (table == "" and iteratorTimes == 1):
                return [{}]
            else:
                return table
        if occurTimes == 1:
            if table == "" and iteratorTimes == 0:
                return 0
            if table is None or isinstance(table, list) is False or len(table) == 0 \
                    or (table == "" and iteratorTimes == 1):
                return [{}]
            else:
                return table
    except:
        return [{}]

def NaNCheck(str):
    return False if str in null_type_list else True

def intCheck(str):
    try:
        int(str)
        return True
    except:
        return False

def Formate(time):
    r = re.compile(r'\D+')
    try:
        date = datetime.datetime.strptime(time, '%Y.%m.%d').strftime('%Y-%m-%d')
    except:
        try:
            date = datetime.datetime.strptime(time, '%Y-%m-%d').strftime('%Y-%m-%d')
        except:
            try:
                date = datetime.datetime.strptime(time, '%Y/%m/%d').strftime('%Y-%m-%d')
            except:
                try:
                    tmp = r.sub('', time)
                    if len(tmp) == 6:
                        date = datetime.datetime.strptime(tmp, '%Y%m').strftime('%Y-%m-%d')
                    else:
                        date = datetime.datetime.strptime(tmp, '%Y%m%d').strftime('%Y-%m-%d')
                except:
                    date = None
    return date

def past6Mon(time):
    time = time.replace('-', '')
    past6ago = datetime.date.today() - datetime.timedelta(days=180)
    past6ago = past6ago.strftime('%Y%m%d')
    return time >= past6ago

# 个人近6个月贷款审批查询机构数
# "Factor1 = 查询记录（POQ)/查询记录信息单元(PH01)/查询日期 PH010R01 在申请日期6个月内
# 且 查询原因代码（PH010Q03）==""02""的 查询机构（PH010Q02）
# Factor =distinct count （Factor1）"
# POQ[1.1] - PH01[0.*] - PH010R01 [1.1] / PH010Q03 [1.1] / PH010Q02 [1.1]

def IC_Past6MonsLoanApprovalQueryOrgCnt():
    data = IC_DSJ.get('data')
    factor = set()
    zero = 0
    # 查询记录 POQ [1.1]
    POQ = getTable(data, 'POQ', 1, 0)
    if POQ == [{}]:
        return u'缺失值'
    elif POQ == 0:
        return 0
    else:
        # 查询记录信息单元 PH01 [0.*]
        PH01 = getTable(POQ[0], 'PH01', 0, 1)
        if PH01 == [{}]:
            return u'缺失值'
        elif PH01 == 0:
            return 0
        else:
            for i in PH01:
                # 查询日期 PH010R01 [1.1] in 1/6/12/24 mons
                PH010R01 = i.get('PH010R01')
                # 查询原因代码 PH010Q03 [1.1] == '02'
                PH010Q03 = i.get('PH010Q03')
                if not (NaNCheck(PH010Q03) and intCheck(PH010Q03)) and Formate(PH010R01) is None:
                    # 缺失值
                    factor.add(None)
                else:
                    if PH010Q03 == '02' and past6Mon(Formate(PH010R01)):
                        # 查询机构 PH010Q02 [1.1]
                        PH010Q02 = i.get('PH010Q02')
                        if not NaNCheck(PH010Q02):
                            # 缺失值
                            factor.add(None)
                        else:
                            factor.add(PH010Q02)
                    else:
                        # 不是缺失值，只是不符合条件
                        factor.add(0)
                        zero = -1

    factor = [x for x in factor if x is not None]
    return u'缺失值' if len(factor) == 0 else len(factor) + zero

if __name__ == '__main__':
    file_obj = open(r'IC_DSJ.json', 'r')
    content = file_obj.read()
    IC_DSJ = json.loads(content, strict=False)
    IC_DSJ = IC_DSJ.get('IC_DSJ')
    res = IC_Past6MonsLoanApprovalQueryOrgCnt()
    print(res)

result = IC_Past6MonsLoanApprovalQueryOrgCnt()